package me.bincker.formwork.web.core.controller

import me.bincker.formwork.web.utils.ResponseUtils
import org.springframework.validation.BindException
import org.springframework.validation.BindingResult
import org.springframework.validation.FieldError
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import java.lang.RuntimeException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@ControllerAdvice
class BindExceptionAdviceController {
    @ExceptionHandler(BindException::class, MethodArgumentNotValidException::class)
    fun handler(request: HttpServletRequest, response: HttpServletResponse, e: Exception){
        val bindingResult = if(e is BindException){
            e.bindingResult
        }else if(e is MethodArgumentNotValidException){
            e.bindingResult
        }else throw RuntimeException("未知的异常：${e::class}")
        ResponseUtils.sendError(data = mutableMapOf(Pair("errorFields", bindingResult.allErrors.map { objectError->
            if(objectError is FieldError){
                mapOf(
                        Pair("field", objectError.field),
                        Pair("message", objectError.defaultMessage)
                )
            }else {
                mapOf(
                        Pair("code", objectError.code),
                        Pair("message", objectError.defaultMessage)
                )
            }
        })))
    }
}